package com.epfresh.supplier.receiver;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.MessageCentre;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.utils.SoundPlayUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.H5OrderDetailActivity;
import com.epfresh.supplier.activity.*;
import com.epfresh.supplier.activity.OrderMoreActivity;
import com.epfresh.supplier.activity.WebActivity;
import com.epfresh.supplier.constant.Constant;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
        /*
        * 订单状态变化1  订单详情页面
        * 下订单2
        * 退款成功3
        * 交易完成4
        * 超时取消5
        * 拒收6
        * 活动7
        * 极光字段：JPushInterface.EXTRA_TITLE EXTRA_MESSAGE EXTRA_EXTRA EXTRA_CONTENT_TYPE
        * */
public class PushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    NotificationManager notificationManager;


    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "[PushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
        if (notificationManager == null)
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[PushReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[PushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
//			JPushInterface.clearAllNotifications(context);
            String title = bundle.getString(JPushInterface.EXTRA_TITLE);
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            //T.toast("rev_msg:" + notifactionId + ":" + message);
//
//			JPushLocalNotification jPushLocalNotification = new JPushLocalNotification();
//			jPushLocalNotification.setTitle(title+"");
//			jPushLocalNotification.setContent(message+"");
//
//			jPushLocalNotification.getNotificationId();

            processCustomMessage(context, bundle);
//			long notificationId = MessageCentre.getInstance().getNotificationId();
//			if (notificationId == -1) {
//				MessageCentre.getInstance().setNotificationId(jPushLocalNotification.getNotificationId());
//			}else {
//				jPushLocalNotification.setNotificationId(notificationId);
//			}
//			notificationId = MessageCentre.getInstance().getNotificationId();
//			JPushInterface.addLocalNotification(context,jPushLocalNotification);
//			JPushInterface.
//			notificationManager.
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[PushReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            String message = bundle.getString(JPushInterface.EXTRA_ALERT);
            String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Log.e(TAG, "[PushReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            Log.e(TAG, "[PushReceiver] 接收到推送下来的通知的message: " + message);
            Log.e(TAG, "[PushReceiver] 接收到推送下来的通知的extra: " + extra);
            //T.toast("rev:" + notifactionId + ":" + message);
//            int count = MessageCentre.getInstance().addOrderCount();
//            JPushInterface.clearNotificationById(context,notifactionId);
//            mergeNotification(context,title,"您有"+count+"张订单产生了变化，请查看"+message);
//            JPushLocalNotification jPushLocalNotification = new JPushLocalNotification();
//			jPushLocalNotification.setTitle("");
//
//
//            jPushLocalNotification.setContent(message+"--11");
//            long notificationId = MessageCentre.getInstance().getNotificationId();
//			if (notificationId == -1) {
//				MessageCentre.getInstance().setNotificationId(99);
//			}
//            jPushLocalNotification.setNotificationId(99);
//            JPushInterface.addLocalNotification(context,jPushLocalNotification);

            if (extra != null && !"".equals(extra)) {
                Map<String, String> map = new Gson().fromJson(extra, new TypeToken<Map<String, String>>() {
                }.getType());
                if (map != null) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        String key = entry.getKey().toString();
                        String value = entry.getValue().toString();
                        System.out.println("key=" + key + " value=" + value);
                    }


                    String sound = map.get("sound");
                    //sound
                    if (sound != null && !"".equals(sound))
                        SoundPlayUtils.playSound(sound);

                    if("receiveOffer".equals(sound)){
                        MessageCentre.getInstance().updateOfferHint(message);
                        return;
                    }

                    //订单状态发生变化,更新首页订单数量接口
                    String code = map.get("code");
                    if (code != null && ("1".equals(code)|| "2".equals(code))){
                        MessageCentre.getInstance().updateOrders();
                    }

                    //source/storeId
                }
            }


        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[PushReceiver] 用户点击打开了通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);

            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
            String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            //source/storeId
            if (extra != null && !"".equals(extra)) {
                Map<String, String> map = new Gson().fromJson(extra, new TypeToken<Map<String, String>>() {
                }.getType());
                if (map != null) {
                    String orderId = map.get("orderId");
                    String link = map.get("link");
                    String storeId = map.get("storeId");
                    //0,线上,1,线下,2,现场
                    String source = map.get("parentSource");
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        String key = entry.getKey().toString();
                        String value = entry.getValue().toString();
                        System.out.println("key=" + key + " value=" + value);
                    }
                    String sound = map.get("sound");
                    if("receiveOffer".equals(sound)){
                        Intent i = new Intent(context, OfferListActivity.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);
                        return;
                    }


                    if (orderId != null && !"".equals(orderId) && ApplicationHelper.getInstance().getUser() != null && ApplicationHelper.getInstance().getUser().getAccess_token() != null && !"".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
                        String sId = BaseApplication.getInstance().getStoreId();
                        if (storeId != null && !"".equals(storeId) && storeId.equals(sId)) {
                            if ("null".equals(orderId)) {
                                //Intent i = new Intent(context, OrderListActivity.class);
                                Intent i = new Intent(context, OrderMoreActivity.class);
                                i.putExtra(Constant.TYPE, 5);
                                //startActivity(intent);
                                i.putExtra("orderType", Integer.parseInt(source));

//                            i.putExtra("id", orderId);
////                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            i.putExtra("pushType", BaseApplication.isHomeActivityAlive ? 1 : 0);
                                context.startActivity(i);
                            } else {
                                //打开自定义的Activity
                                Intent i = new Intent(context, H5OrderDetailActivity.class);
                                i.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_TITLE, "订单详情");
                                i.putExtra("orderId", orderId);
//                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                i.putExtra("pushType", BaseApplication.isHomeActivityAlive ? 1 : 0);
                                context.startActivity(i);
                            }
                        }
                    } else if (link != null && !"".equals(link)) {
                        //打开自定义的Activity
                        Intent i = new Intent(context, WebActivity.class);
                        i.putExtra(Constant.KEY_WEB_URL, link);
                        i.putExtra(Constant.KEY_WEB_TITLE, title);
//                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.putExtra("pushType", BaseApplication.isHomeActivityAlive ? 1 : 0);
                        context.startActivity(i);
                    }
                }
            }
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[PushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[PushReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else if ("com.epfresh.notification.open".equals(intent.getAction())) {
            //T.toast("open--------------------" );
            MessageCentre.getInstance().resetOrderCount();
        } else {
            Log.d(TAG, "[PushReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    private void mergeNotification(Context context, String title, String content) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
        mBuilder.setSmallIcon(R.mipmap.supplier_logo)
                .setContentTitle(title)
                .setContentText(content);
        Intent resultIntent = new Intent("com.epfresh.notification.open");
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
//        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
//        stackBuilder.addParentStack(HomeActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
//        stackBuilder.addNextIntent(resultIntent);
//        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


        PendingIntent p = PendingIntent.getBroadcast(context, 0, resultIntent, 0);
        mBuilder.setContentIntent(p);
        mBuilder.setAutoCancel(true);
        if (notificationManager == null)
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
        notificationManager.notify(99, mBuilder.build());
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
//		if (HomeActivity.isForeground) {
//			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
//			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
//			if (!ExampleUtil.isEmpty(extras)) {
//				try {
//					JSONObject extraJson = new JSONObject(extras);
//					if (null != extraJson && extraJson.length() > 0) {
//						msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
//					}
//				} catch (JSONException e) {
//
//				}
//
//			}
//			context.sendBroadcast(msgIntent);
//		}
    }


}
